/* 
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Contributor(s):
 *   Lan Qiang <jameslan@gmail.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK *****
 */

#include "nsZipOutputStream.h"
#include "nsZipEntryIndex.h"
#include "zipformat.h"

NS_IMPL_THREADSAFE_ISUPPORTS1(nsZipOutputStream, nsIOutputStream)

NS_IMETHODIMP
nsZipOutputStream::Close()
{
	if (mClosed) {
		return NS_OK;
	}

	nsresult rv;

	if (mDeflate) {
		int zerr;
		do {
			zerr = deflate(&(mDeflate->mZs), Z_FINISH);
			// TODO check whether output size smaller than input size
			rv = Flush();
			NS_ENSURE_SUCCESS(rv, rv);
		} while (zerr == Z_OK);

		deflateEnd(&(mDeflate->mZs));

		mItem->size = mDeflate->mZs.total_out;
		mItem->realSize = mDeflate->mZs.total_in;

		PR_FREEIF(mDeflate);
	} else {
		mItem->size = mOutSize;
		mItem->realSize = mCurPos;
	}
	mItem->itemCRC32 = mInCrc;
	mZipIO->mCentralDirPos = mItem->dataOffset + mItem->size;

	//-- Set filepointer to start of item's local file header
	if (PR_Seek(mFd, mItem->offset, PR_SEEK_SET) < 0) {
		return NS_ERROR_FILE_CORRUPTED;
	}

	rv = mIndex->WriteLocalHeader(mItem);
	NS_ENSURE_SUCCESS(rv, rv);

	rv = mIndex->InsertIntoHashTable(mItem);
	NS_ENSURE_SUCCESS(rv, rv);

	mFd = nsnull;
	mClosed = PR_TRUE;

	return NS_OK;
}

NS_IMETHODIMP
nsZipOutputStream::Flush()
{
	NS_ASSERTION(mFd, "File handle missing");
	PRUint32 bytesToWrite = ZIP_BUFLEN - mDeflate->mZs.avail_out;
	if ((PRUint32)PR_Write(mFd, mDeflate->mWriteBuf, bytesToWrite) < bytesToWrite) {
		return NS_ERROR_FILE_DISK_FULL;
	}

	// now set the state for 'deflate'
	mDeflate->mZs.next_out = mDeflate->mWriteBuf;
	mDeflate->mZs.avail_out = ZIP_BUFLEN;

	return NS_OK;
}

NS_IMETHODIMP
nsZipOutputStream::Write(const char *aBuf, PRUint32 aCount, PRUint32 *_retval)
{
	NS_ENSURE_ARG_POINTER(aBuf);
	NS_ENSURE_ARG_POINTER(_retval);

	*_retval = 0;

	nsresult rv = NS_OK;
	if (mClosed)
		return rv;

	// Calculate the CRC on the input
	mInCrc = crc32(mInCrc, (unsigned char*)aBuf, aCount);

	if (mDeflate) { // DEFLATED
		rv = ContinueDeflate(aBuf, aCount, _retval);
	} else { // STORED
		PRInt32 bytesWritten = 0;
		if (aCount) {        
			bytesWritten = PR_Write(mFd, aBuf, aCount);
			if (bytesWritten < 0)
				return NS_ERROR_FILE_CORRUPTED;
			mCurPos += bytesWritten;
			mOutSize += bytesWritten;
		}
		*_retval = bytesWritten;
	}

	return rv;
}

NS_IMETHODIMP
nsZipOutputStream::WriteFrom(nsIInputStream *aFromStream, PRUint32 aCount, PRUint32 *_retval)
{
	return NS_ERROR_NOT_IMPLEMENTED;
}

NS_IMETHODIMP
nsZipOutputStream::WriteSegments(nsReadSegmentFun aReader, void * aClosure, PRUint32 aCount, PRUint32 *_retval)
{
	return NS_ERROR_NOT_IMPLEMENTED;
}

NS_IMETHODIMP
nsZipOutputStream::IsNonBlocking(PRBool *_retval)
{
    *_retval = PR_FALSE;
    return NS_OK;
}

nsresult nsZipOutputStream::Init(nsZipFileIO* aZip, nsZipEntryItem *item,
		nsZipEntryIndex *index, PRFileDesc *fd, nsZipFileIO *zipio,
		nsZipLevel compression)
{
	nsresult rv;

	NS_ENSURE_ARG_POINTER(aZip);
	NS_ENSURE_ARG_POINTER(item);
	NS_ENSURE_ARG_POINTER(fd);

	// Mark it as closed, in case something fails in initialisation
	mClosed = PR_TRUE;

	mFd = fd;
	mIndex = index;
	mZipIO = zipio;

	mCurPos = mOutSize = 0;
	mItem = item;
	mInCrc = crc32(0L, Z_NULL, 0);

	//-- prepare for the compression type
	int zerr;
	switch (item->compression) {
	case STORED: 
		break;

	case DEFLATED:
		mDeflate = (DeflateStruct *) PR_Malloc(sizeof(DeflateStruct));
		NS_ENSURE_TRUE(mDeflate, NS_ERROR_OUT_OF_MEMORY);

		rv = gZlibInit(&(mDeflate->mZs));
		NS_ENSURE_SUCCESS(rv, NS_ERROR_OUT_OF_MEMORY);
		zerr = deflateInit2(&mDeflate->mZs,
				compression,
				Z_DEFLATED,
				-MAX_WBITS,
				8,
				Z_DEFAULT_STRATEGY);
		if (zerr != Z_OK) return NS_ERROR_OUT_OF_MEMORY;

		mDeflate->mZs.next_out = mDeflate->mWriteBuf;
		mDeflate->mZs.avail_out = ZIP_BUFLEN;
		break;

	default:
		return NS_ERROR_NOT_IMPLEMENTED;
	}

	//-- Set filepointer to start of item's local file header
	if (PR_Seek(mFd, item->offset, PR_SEEK_SET) < 0) {
		return NS_ERROR_FILE_CORRUPTED;
	}

	rv = mIndex->WriteLocalHeader(mItem);
	NS_ENSURE_SUCCESS(rv, rv);

	// Open for reading
	mClosed = PR_FALSE;
	return NS_OK;
}

nsresult 
nsZipOutputStream::ContinueDeflate(const char* aBuffer, PRUint32 aCount,
                                  PRUint32* aBytesWrite)
{
	// No need to check the args, ::Read did that, but assert them at least
	NS_ASSERTION(mDeflate,"deflate data structure missing");
	NS_ASSERTION(aBuffer,"aBuffer parameter must not be null");
	NS_ASSERTION(aBytesWrite,"aBytesWrite parameter must not be null");

	// Keep old total_out count
	const PRUint32 oldTotalOut = mDeflate->mZs.total_out;

	// make sure we aren't reading too much
	mDeflate->mZs.avail_in = aCount;
	mDeflate->mZs.next_in = (unsigned char*)aBuffer;

	*aBytesWrite = 0;
	int zerr = Z_OK;
	// deflate loop
	while (mDeflate->mZs.avail_in > 0 && zerr == Z_OK) {
		zerr = deflate(&(mDeflate->mZs), Z_NO_FLUSH);

		while (mDeflate->mZs.avail_out == 0) {
			// buffer is full, time to write it to disk!
			nsresult rv = Flush();
			NS_ENSURE_SUCCESS(rv, rv);
			zerr = deflate(&(mDeflate->mZs), Z_NO_FLUSH);
		}
	}

	*aBytesWrite = (mDeflate->mZs.total_out - oldTotalOut);

	return NS_OK;
}
